import { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { toast } from "sonner";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { PageContainer } from "@/layouts/PageContainer";
import { userService } from "@/service/userService";
import { useAuth } from "@/context/AuthContext";
import { UserAuth } from "@/types/user";




export default function Login() {
  const [formData, setFormData] = useState({
    email: "",
    password: "",
  });
  const [isLoading, setIsLoading] = useState(false);
  const { login } = useAuth();
  const navigate = useNavigate();

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);

    try {
      const response = await userService.login(formData);

      if (response.code === 0) {
        // TypeScript类型守卫确保data存在
        const { token, user } = (response as { code: 0; data: UserAuth }).data;
        login(token, user);
        toast.success("登录成功！");

        // 登录成功后重定向到首页
        setTimeout(() => {
          navigate("/");
        }, 1500);
      } else {
        // TypeScript类型守卫确保message存在
        const errorMsg = (response as { code: number; message: string }).message;
        toast.error(errorMsg || "登录失败，请检查邮箱和密码");
      }
    } catch (error) {
      console.error("登录出错:", error);
      toast.error("登录过程中发生错误，请稍后重试");
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <PageContainer centered>
      <Card className="w-full max-w-md shadow-xl">
        <CardHeader className="space-y-2">
          <CardTitle className="text-center text-2xl">欢迎回来</CardTitle>
          <CardDescription className="text-center">
            登录您的账户以继续
          </CardDescription>
        </CardHeader>
        <form onSubmit={handleSubmit}>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="email">邮箱</Label>
              <Input
                id="email"
                name="email"
                placeholder="请输入邮箱"
                required
                value={formData.email}
                onChange={handleChange}
                disabled={isLoading}
              />
            </div>
            <div className="space-y-2">
              <div className="flex justify-between items-center">
                <Label htmlFor="password">密码</Label>
                <Link
                  to="/auth/forgot-password"
                  className="text-xs text-blue-400 hover:underline"
                >
                  忘记密码?
                </Link>
              </div>
              <Input
                id="password"
                name="password"
                type="password"
                placeholder="请输入密码"
                required
                value={formData.password}
                onChange={handleChange}
                disabled={isLoading}
              />
            </div>
          </CardContent>
          <CardFooter className="flex flex-col space-y-4 mt-4">
            <Button
              type="submit"
              className="w-full"
              disabled={isLoading}
            >
              {isLoading ? "登录中..." : "登录"}
            </Button>
            <div className="text-center text-sm">
              还没有账户?{" "}
              <Link to="/auth/register" className="text-blue-400 hover:underline">
                立即注册
              </Link>
            </div>
          </CardFooter>
        </form>
      </Card>
    </PageContainer>
  );
} 